/**
 * Definition for singly-linked list. */
function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
const addTwoNumbers = function(l1, l2) {
    let head = null, tail = null;
    let carry = 0;
    while (l1 || l2) {
        const n1 = l1 ? l1.val : 0;
        const n2 = l2 ? l2.val : 0;
        const sum = n1 + n2 + carry;
        if (!head) {
            head = tail = new ListNode(sum % 10);
        } else {
            tail.next = new ListNode(sum % 10);
            tail = tail.next;
        }
        carry = Math.floor(sum / 10);
        if (l1) {
            l1 = l1.next;
        }
        if (l2) {
            l2 = l2.next;
        }
    }
    if (carry > 0) {
        tail.next = new ListNode(carry);
    }
    return head;

};

/*
class ListNode {
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}
* */


function stringToListNode(str) {
    if (!str) {
        return null;
    }
    if (str.startsWith("[") && str.endsWith("]")) {
        str = JSON.parse(str);
    }
    if (Array.isArray(str)) {
        console.log(str);
    }

    let head = new ListNode(str[0]);
    let curr = head;

    for (let i = 1; i < str.length; i++) {
        let node = new ListNode(str[i]);
        curr.next = node;
        curr = node;
    }

    return head;
}

// let str = "[2,1,5]";
// let head = stringToListNode(str);
// console.log(head);
// ListNode { val: 'h', next: ListNode { val: 'e', next: ListNode { val: 'l', next: ListNode { val: 'l', next: ListNode { val: 'o', next: null } } } } } }

/*
"[2,1,5]"

ListNode {
  val: 2,
  next: ListNode { val: 1, next: ListNode { val: 5, next: null } }
}
* */

// let s1 = "[2,4,3]";
// let l1 = stringToListNode(s1);
// console.log("l1: ", l1);
// let s2 = "[5,6,4]";
// let l2 = stringToListNode(s2);
// console.log("l2: ", l2);
// let s3 = "[7,0,8]";
// let expected = stringToListNode(s3);
// console.log("expected: ", expected);
//
// let root = addTwoNumbers(l1, l2);
// console.log("root: ", root);
// // root:  [object Object]
// console.log("root: ", root.toString());

/*
这种脚本，其它文件调用的时候，会运行的！
* */

module.exports = addTwoNumbers;



